package com.crossriver.crgis.portlet;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.crossriver.crgis.cofo.util.Emailer;
import com.crossriver.crgis.database.model.Application_C_of_O;
import com.crossriver.crgis.database.model.Bank_Payment_Slip;
import com.crossriver.crgis.database.model.Company_Contact_Person;
import com.crossriver.crgis.database.model.Contact_Information;
import com.crossriver.crgis.database.model.Individual_Information;
import com.crossriver.crgis.database.model.Transactions;
import com.crossriver.crgis.database.service.Application_C_of_OLocalServiceUtil;
import com.crossriver.crgis.database.service.Bank_Payment_SlipLocalServiceUtil;
import com.crossriver.crgis.database.service.Company_Contact_PersonLocalServiceUtil;
import com.crossriver.crgis.database.service.Contact_InformationLocalServiceUtil;
import com.crossriver.crgis.database.service.Individual_InformationLocalServiceUtil;
import com.crossriver.crgis.database.service.TransactionsLocalServiceUtil;
import com.crossriver.crgis.mail.util.MailMessages;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.servlet.SessionErrors;
import com.liferay.portal.kernel.util.Base64;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.util.bridges.mvc.MVCPortlet;

/**
 * Portlet implementation class BankPaymentSlip
 */
public class BankPaymentSlip extends MVCPortlet {
	
	private static Log log = LogFactory.getLog(BankPaymentSlip.class);
 
	@Override
	public void serveResource(
			ResourceRequest resourceRequest, ResourceResponse resourceResponse)
		throws IOException, PortletException { 
		
		String queryType= ParamUtil.getString(resourceRequest, "queryType");
		
		
		if (queryType.equalsIgnoreCase("viewPaymentSlip")){
			//
			String slipNo = ParamUtil.getString(resourceRequest, "slipNo");
			
			//retrieve the info 
			try {
				Bank_Payment_Slip bankSlip = Bank_Payment_SlipLocalServiceUtil.getBank_Payment_Slip(slipNo);
				
				
				resourceResponse.setProperty("Content-Disposition", "attachment; filename=" + bankSlip.getUploadDepositSlipFilename());
	        	
				
				byte[] readStream = Base64.decode(bankSlip.getUploadDepositSlip());
	    		
				resourceResponse.setProperty("Content-Disposition", "attachment; filename=" + bankSlip.getUploadDepositSlipFilename() );
	        	
				resourceResponse.getPortletOutputStream().write(readStream);
	    		
	    		return;
			} catch (PortalException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			return;
		}
	}
	
	public void displayPaySlip(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		String slipNo = actionRequest.getParameter("slipNo");
		
		Bank_Payment_Slip bankSlip = null;
		
		try {
			bankSlip = Bank_Payment_SlipLocalServiceUtil.getBank_Payment_Slip(slipNo);
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		actionRequest.setAttribute("bankSlip", bankSlip);
		
		String bankSlipView =  "/html/bankpaymentslip/viewBankSlip.jsp";
		 
		
		actionRequest.setAttribute("jspPage", bankSlipView);
		actionResponse.setRenderParameter("jspPage", bankSlipView);

	}
	
	public void cancel(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		String slipNo = actionRequest.getParameter("slipNo");
		
		Bank_Payment_Slip bankSlip = null;

	}

	public void confirmed(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		String slipNo = actionRequest.getParameter("slipNo");
		
		try {
			Bank_Payment_Slip bankSlip = Bank_Payment_SlipLocalServiceUtil.getBank_Payment_Slip(slipNo);
			
			bankSlip.setStatus("CONFIRMED");
			
			//create a transaction out of this
			
			String transNo = UUID.randomUUID().toString();		
			Transactions  trans = TransactionsLocalServiceUtil.createTransactions(transNo);
			
			Application_C_of_O application = Application_C_of_OLocalServiceUtil.getApplication_C_of_O(bankSlip.getApplicationId());
			
			trans.setUserId(bankSlip.getUserId());
			
			trans.setTransactionRef(application.getReferenceNo() + "-" + application.getDateOfApplication());
			trans.setItemId(application.getReferenceNo());
			
			String itemDescription = "Application Fees " + application.getApplication() + "-" + application.getApplicationType();
			trans.setItemDescription(itemDescription);
			
			trans.setPaymentType("Bank Deposit");
			trans.setPaymentDate(bankSlip.getRegistedDate());
			trans.setReceiptNo(bankSlip.getDepSlipNo());
			trans.setAmount(bankSlip.getPaidAmount());
			trans.setApprovedAmount(bankSlip.getApprovedAmount());
			trans.setBankName(bankSlip.getBankName());
			trans.setTransactionFee(0.00);
			trans.setRetRef(bankSlip.getDepSlipNo());
			
			trans.setStatus("COMPLETE");
			
			System.out.println(trans.toString());
			System.out.println("");
			
			Bank_Payment_SlipLocalServiceUtil.updateBank_Payment_Slip(bankSlip, true);
			
			//
			application.setStatus("PAYMENT_MADE");
			Application_C_of_OLocalServiceUtil.updateApplication_C_of_O(application, true);
			
			TransactionsLocalServiceUtil.updateTransactions(trans, true);
			
			Bank_Payment_SlipLocalServiceUtil.updateBank_Payment_Slip(bankSlip, true);
			
			//Send confirmation mail
			
			String message = MailMessages.PAYMENT_CONFIRMATION;
			
			String applicationId = 	application.getApplicationId();
			
			Contact_Information contact = Contact_InformationLocalServiceUtil.getContact_Information(applicationId);
			
			String appType = application.getApplicationType();
			String emailAddr = contact.getEmailAddress();
			
			if("Individual".equalsIgnoreCase(appType)){
				
				Individual_Information individual = Individual_InformationLocalServiceUtil.getIndividual_Information(applicationId);
				
				message = message.replaceAll("#CLIENT_NAME#", individual.getLastName() + " " + individual.getFirstName());
				message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());		
			}else{
				
				Company_Contact_Person coyContact = Company_Contact_PersonLocalServiceUtil.getCompany_Contact_Person(applicationId);
				
				message = message.replaceAll("#CLIENT_NAME#", coyContact.getLastName() + " " + coyContact.getFirstName());
				message = message.replaceAll("#EMAIL_ADDR#", contact.getEmailAddress());
			}
			
			message = message.replaceAll("#REF_CODE#", trans.getPayRef());
			message = message.replaceAll("#TRANS_REF_CODE#", trans.getTransactionRef());
			message = message.replaceAll("#NAME_OF_TRANS#", trans.getItemDescription());
			message = message.replaceAll("#TRANS_AMT#", trans.getAmount().toString());
			message = message.replaceAll("#TRANS_ID#", trans.getItemId());
			 
			//send mail to the CRGIS for notification of of completed application
			String from ="crgis@crossriverstate.gov.ng";
			String to = emailAddr;
			String bcc=null;
			String subject  =  application.getApplication().toUpperCase() + " - " + application.getReferenceNo() ;
			
			File[] attachments = null;
			
			try {
				Emailer.sendEmail(from, to, bcc, subject, message, attachments );
			} catch (Exception e) {
				SessionErrors.add(actionRequest, "problem-sending-mail");
				if(log.isInfoEnabled()){
					log.info(e.getMessage());
				}
				e.printStackTrace();
			}
			
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}
	
	public void unconfirmed(ActionRequest actionRequest, 
			ActionResponse actionResponse){
		String slipNo =   ParamUtil.getString(actionRequest, "slipNo");
		
		try {
			Bank_Payment_Slip bankSlip = Bank_Payment_SlipLocalServiceUtil.getBank_Payment_Slip(slipNo);
			
			bankSlip.setStatus("UNCONFIRMED");
			
			Bank_Payment_SlipLocalServiceUtil.updateBank_Payment_Slip(bankSlip, true);
			
		} catch (PortalException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * This method is used to override the addSuccessMessage in the parent
	 * class. This override ensures that success message (that is displayed as
	 * default whenever any request is successfully submitted) is prevented.
	 * 
	 * We like to have control over this and this what this override ensures.
	 * 
	 */
	@Override
	protected void addSuccessMessage(ActionRequest actionRequest,
			ActionResponse actionResponse) {

		if (!addProcessActionSuccessMessage) {
			return;
		}
	}
}
